/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package network;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import lib.Core;
import lib.Money;
import lib.XmlPullParser;
import ru.qiwi.security.MD5;
import ru.qiwi.security.Security;
import Core.Contants;
import Core.GlobalData;
import Core.PaymentsLogic;
import DTO.PurchaseOnline;
import DTO.TransferElement;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;

import com.simpay.cashierandroidapp.DialogScreen;
import com.simpay.cashierandroidapp.R;
import com.simpay.login.CreatePincodeActivity;
import com.simpay.login.MainActivity;

/**
 * 
 * @author HOME
 */
public class NetworkThread  extends Thread{

	private String stringURL;
	private Packet packet;
	int idpacket;
	int next;
	Object data;

	public NetworkThread(int idpacket, int next) {
		this.stringURL = GlobalData.url;
		this.idpacket = idpacket;
		this.packet = new Packet(idpacket, Core.context, null);
		this.next = next;		
		start();
	}

	public NetworkThread(int idpacket, int next, Object data) {
		this.data = data;
		this.stringURL = GlobalData.url;
		this.idpacket = idpacket;
		this.packet = new Packet(idpacket, Core.context, null);
		this.next = next;	
		
		start();
	}

	public void run() {

		HttpURLConnection hc = null;
		InputStream in = null;
		OutputStream out = null;
		try {
			System.out.println("__________Connect Server___________");
			if (idpacket == Packet.TYPE_HEADNUMBER) {
				URL url = new URL(
						"http://qcm.simpay.com.vn/download/headnumber.xml");
				hc = (HttpURLConnection) url.openConnection();
				in = hc.getInputStream();
				XmlPullParser xml = new XmlPullParser(new InputStreamReader(in,
						"UTF-8"));
				packet.parseXML(xml);
			} else if (idpacket == Packet.TYPE_PRICETYPES) {
				URL url = new URL("http://qcm.simpay.com.vn/download/price.xml");
				hc = (HttpURLConnection) url.openConnection();
				in = hc.getInputStream();
				XmlPullParser xml = new XmlPullParser(new InputStreamReader(in,
						"UTF-8"));
				packet.parseXML(xml);
			}
			// TEST MA THE
			// else if (idpacket == Packet.TYPE_PURCHASEONLINE) {
			// sleep(3000);
			// System.out.println("_____________________");
			// String message = packet.toXML();
			// System.out.println("request" + message);
			//
			// in = new ByteArrayInputStream(getTestPurchaseOnline()
			// .getBytes());
			// XmlPullParser xml = new XmlPullParser(new InputStreamReader(in,
			// "UTF-8"));
			// packet.parseXML(xml);
			// }
			else {

				String message = packet.toXML();
				System.out.println("request" + message);

				URL url = new URL(stringURL);
				hc = (HttpURLConnection) url.openConnection();
				hc.setDoInput(true);
				hc.setDoOutput(true);
				hc.setUseCaches(false);
				hc.setRequestProperty("Content-Type", "text/xml");
				hc.setRequestProperty("Content-Length",
						String.valueOf(message.length()));

				if (idpacket == Packet.TYPE_SETPUBLICKEY) {
					hc.setRequestProperty("X-Digital-Sign",
							MD5.hashAsHex(GlobalData.auth.getSign()));//
					hc.setRequestProperty("X-Digital-Sign-Alg",
							GlobalData.auth.getSignAlg());
					hc.setRequestProperty("X-Digital-Sign-Login",
							GlobalData.auth.getLogin());
				} else {
					String userCredentials = Security.getIns().getSign(
							message.getBytes("UTF-8"));
					hc.setRequestProperty("X-Digital-Sign", userCredentials);
					hc.setRequestProperty("X-Digital-Sign-Alg", "MD5withRSA");
					hc.setRequestProperty("X-Digital-Sign-Login",
							GlobalData.auth.getLogin());
				}

				out = hc.getOutputStream();
				out.write(message.getBytes("UTF-8"));
				in = hc.getInputStream();
				//
				byte[] b = GlobalData.log2(in);
				System.out.println("response" + new String(b));
				InputStream is = new ByteArrayInputStream(b);
				//
				if (hc.getResponseCode() == 200) {
					XmlPullParser xml = new XmlPullParser(
							new InputStreamReader(is, "UTF-8"));
					packet.parseXML(xml);
				}
			}
		} catch (Exception e) {			
			System.out.println("Exception at NetworkThread:" + e.getMessage());
			processException(e);
			exceptionToSimpay();
		} finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
				if (hc != null) {
					hc.disconnect();
				}
			} catch (IOException e) {
			}

		}
	}

	private void processException(Exception e) {
		// String error_message = null;
		// int errorID = -1;
		// try {
		// errorID = Integer.parseInt(e.getMessage());
		// } catch (Exception ex) {
		// }
		//
		// if (idpacket == Packet.TYPE_GETPAYMENTSTATUS) {
		// System.out.println("exception get payment status............");
		// LiveThread.send_queue = true;
		// } else if (idpacket == Packet.TYPE_SENDPAYMENTS && current == null) {
		// LiveThread.send_request = true;
		// } else if (idpacket == Packet.TYPE_PURCHASEONLINE && current == null)
		// {
		// LiveThread.send_po = true;
		// } else if (idpacket == Packet.TYPE_SENDPAYMENTS && current != null) {
		// AppEntity.event(AppEntity.E_SENDOP_ERROR, null);
		// LiveThread.send_request = true;
		// } else if (idpacket == Packet.TYPE_PURCHASEONLINE && current != null)
		// {
		// AppEntity.event(AppEntity.E_SENDOP_ERROR, null);
		// LiveThread.send_po = true;
		// } else if (idpacket == Packet.TYPE_GETMESSAGES) {
		// LiveThread.send_mess = true;
		// } else {
		//
		// if (errorID != -1 && errorID != 150) {
		// if (GlobalData.errCodeTable != null) {
		// error_message = (String) GlobalData.errCodeTable
		// .get(new Integer(errorID));
		// } else {
		// error_message = Locale.get("s6000");
		// }
		// } else if (errorID == 150) {
		// if (idpacket == Packet.TYPE_SETPUBLICKEY) {
		// Object[] a = new Object[1];
		// a[0] = new Integer(150);
		// AppEntity.event(AppEntity.E_ERR_INFOLOGIN, a);
		// return;
		// } else {
		// if (GlobalData.errCodeTable != null) {
		// error_message = (String) GlobalData.errCodeTable
		// .get(new Integer(errorID));
		// } else {
		// error_message = Locale.get("error.invalid.login");
		// }
		// }
		// } else {
		// error_message = Locale.get("error.url_service");
		// }
		//
		// if (AppEntity.oldDisplayable != null) {
		// AppEntity.midlet.showMessage(Locale.get("s5999") + " #"
		// + errorID + ": " + error_message,
		// AppEntity.oldDisplayable);
		// } else {
		// AppEntity.midlet.showMessage(Locale.get("s5999") + " #"
		// + errorID + ": " + error_message,
		// AppEntity.midlet.getCurrentDisplay());
		// }
		// }

	}

	public void exceptionToSimpay() {
		// if (idpacket == Packet.TYPE_GETGROUPS
		// || idpacket == Packet.TYPE_GETPROVIDERS
		// || idpacket == Packet.TYPE_HEADNUMBER
		// || idpacket == Packet.TYPE_PRICETYPES) {
		// LoadFile.loadResource();
		// AppEntity.event(AppEntity.E_UPDATE_PUI);
		// new LoadURLImage();
		// }
	}

	
	
	

}
